package com.kingbook.api.filter;

import com.kingbook.common.utils.ValidateUtil;
import com.kingbook.core.result.JSONResult;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * XSS攻击过滤器
 */
public class XssFilter implements Filter {
    private FilterConfig filterConfig = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        Enumeration<String> e = request.getHeaderNames();
        boolean flag = true;
        String err = "";
        String k = "";
        String v = "";
        while (e.hasMoreElements()) {
            k = e.nextElement();
            v = request.getHeader(k);
            if (ValidateUtil.hasXssCode(v)) {
                flag = false;
                err += "Request Header  " + k + "=" + v + " Contain Xss Code, ";
            }
        }
        e = request.getParameterNames();
        while (e.hasMoreElements()) {
            k = e.nextElement();
            v = request.getParameter(k);
            if (ValidateUtil.hasXssCode(v)) {
                flag = false;
                err += "Request Parameter  " + k + "=" + v + " Contain Xss Code, ";
            }
        }
        String uri = request.getRequestURL().toString();
        if (ValidateUtil.hasXssCode(uri)) {
            flag = false;
            err += "Request Uri Contain Xss Code, ";
        }

/*        String body = StreamUtils.inputStreamTOString(request.getInputStream());
        if (ValidateUtil.hasXssCode(body)) {
            flag = false;
            err += "Request Body Contain Xss Code, ";
        }*/
        if (flag)
            chain.doFilter(new XssHttpServletRequestWrapper(request), response);
        else {
            response.getWriter().print(JSONResult.failed(err));
        }
    }

}